import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.preprocessing import Normalizer
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score #轮廓系数
plt.rcParams['font.sans-serif']='STSong'
print('-------读取数据---------')
pdt=pd.read_csv('Wholesal_customers_data.csv')
print(pdt.head(5))
print('------统计空的数量------')
isnull_sum=pdt.isnull().sum()
print(isnull_sum)
print('------描述数据------')
des=pdt.describe()
print(des)
#在此使用Normalizer---使用方法同MinMaxScaler、StandardScaler

nl=Normalizer();
std=nl.fit_transform(pdt.iloc[:,2:])
std_=pd.DataFrame(data=std)
print(std_.head(5))
# print(std)
print('------学习曲线------')
print('适用轮廓系数找到最优K')
score=[]
for i in  range(2,20):
    cluter=KMeans(n_clusters=i,random_state=0).fit(std_)
    # print(cluter.labels_)
    score.append(silhouette_score(std_,cluter.labels_))

plt.axvline(pd.DataFrame(score).idxmax()[0]+2,ls=':')

plt.plot(range(2,20),score)
plt.show()

cluter=KMeans(n_clusters=3,random_state=0).fit(std_)
# print(cluter.labels_)
y=cluter.labels_
print('------建模分类--------')
std_['lable']=y
std_.columns=['Fresh','Milk','Grocery','Frozen','Detergents_Paper','Delicassen','lable']
print(std_)
avg=std_.groupby(by='lable').mean()

print(avg)

#饼图
print('------饼图--------')

count=std_.groupby(by='lable')['lable'].count()
print(count)

# print(count.index)

plt.pie(count,autopct='%0.2f%%')
plt.legend(count.index,loc = 'best'
           ,title =
           '分类',)
plt.show()


# sum=std_.groupby(by=['lable']).sum()
# print(sum)
#rect_1 = plt.bar(x_14,day_14,width=bar_width,label = '14日票房',color = 'Magenta')
#rect_2 = plt.bar(x_15,day_15,width=bar_width,label = '15日票房',color = 'Indigo')
#rect_3 = plt.bar(x_16,day_16,width=bar_width,label = '16日票房')
print('--------条形图--------')
bar_width = 0.1
x_14 = list(range(len(avg.index)))
x_15 = [i + bar_width for i in x_14]
x_16 = [i + bar_width*2 for i in x_14]
x_17 = [i + bar_width*3 for i in x_14]
x_18 = [i + bar_width*4 for i in x_14]
x_19 = [i + bar_width*5 for i in x_14]

rect_1 = plt.bar(x_14,avg.Fresh,width=bar_width,label = 'Fresh',color = 'r')
rect_2 = plt.bar(x_15,avg.Milk,width=bar_width,label = 'Milk',color = 'b')
rect_3 = plt.bar(x_16,avg.Grocery,width=bar_width,label = 'Grocery',color = 'darkred')
rect_4 = plt.bar(x_17,avg.Frozen,width=bar_width,label = 'Frozen',color = 'y')
rect_5 = plt.bar(x_18,avg.Detergents_Paper,width=bar_width,label = 'Detergents_Paper',color = 'g')
rect_5 = plt.bar(x_19,avg.Delicassen,width=bar_width,label = 'Delicassen',color = 'Magenta')
plt.legend()
plt.xticks(x_16,avg.index)
plt.show()



